package com.itheima.ai.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.ai.po.ChatHistory;
import com.itheima.ai.mapper.ChatHistoryMapper;
import com.itheima.ai.service.IChatHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mr.wu
 * @since 2025-11-04
 */
@Service
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements IChatHistoryService {




    /**
     * 保存会话历史信息（主要存储业务类型对应的某用户的会话ID）
     *
     * @param type   业务类型：聊天机器人-chat、智能客服-service、知识库-pdf
     * @param chatId 会话ID
     * @param userId 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveHistory(String type, String chatId, Long userId) {

        //先查询是否已有对应数据
        Long count = this.lambdaQuery().eq(userId != null, ChatHistory::getUserId, userId)
                .eq(ChatHistory::getType, type)
                .eq(ChatHistory::getConversationId, chatId)
                .count();
        if(count>0) {
            return;
        }

        //不存在再新增
        ChatHistory chatHistory = ChatHistory.builder()
                .conversationId(chatId)
                .type(type)
                .createTime(LocalDateTime.now())
                .title("对话ID:" + chatId)
                .userId(userId)
                .build();
        this.save(chatHistory);
    }

    /**
     * 根据用户ID和业务类型查询对应的会话ID列表
     * @param type 业务类型：聊天机器人-chat、智能客服-service、知识库-pdf
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<String> findConversationIds(String type, Long userId) {

        List<ChatHistory> chatHistoryList = this.lambdaQuery()
                .eq(ChatHistory::getType, type) //业务场景
                .eq(userId != null, ChatHistory::getUserId, userId)
                .orderByDesc(ChatHistory::getCreateTime)
                .select(ChatHistory::getConversationId)
                .list();
        if(CollUtil.isEmpty(chatHistoryList)) {
            return Collections.emptyList();
        }

        List<String> chatIdList = chatHistoryList.stream()
                .map(ChatHistory::getConversationId)
                .collect(Collectors.toList());

        return chatIdList;
    }
}
